package com.hc.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hc.util.JsonResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;

@Component
public class LoginvalidateInterceptor implements HandlerInterceptor {

    Logger logger = LoggerFactory.getLogger(LoginvalidateInterceptor.class.getName());
    @Override
    //当此方法返回true,表示可以访问控制器相应的方法
    //当返回false时，不会调用控制器的方法，需要开发者自行编写代码返回处理结果
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.debug("拦截器的preHandle方法被调用");

        logger.debug("URI:"+  request.getRequestURI());
        logger.debug("URL:"+  request.getRequestURL());
      // if (!request.getRequestURI().equals("/sysUserController/userLogin")){
            boolean b=   StpUtil.isLogin();
            logger.debug("用户是否已登录"+b);
            if (!b){
               // throw new RuntimeException("您还未登录，请先登录");
                response.setHeader("Content-Type","application/json;charset=utf-8");
                PrintWriter out =  response.getWriter();

                JsonResponse jsonResponse = new JsonResponse();
                jsonResponse.setCode(1);
                jsonResponse.setMsg("您还未登录，请先登录");

                ObjectMapper objectMapper = new ObjectMapper();//Gson gson = new Gson();
                String json  = objectMapper.writeValueAsString(jsonResponse) ;//gson.toJson(jsonResponse);

                out.println(json);

                return  false;
            }
     //   }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        logger.debug("拦截器的postHandle方法被调用");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.debug("拦截器的afterCompletion方法被调用");
    }
}
